package com.hunter.jerrymouse;

import com.hunter.jerrymouse.server.Server;
import com.hunter.jerrymouse.util.SpringBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by hunter
 * <p>
 * 应用启动类
 */
public class ServerStarter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerStarter.class);

    public static void main(String[] args) throws Exception {

        LOGGER.info("Begin to start server.");

        long beginTime = System.currentTimeMillis();

        printLogo();

        initSpring();

        initServer(args);

        LOGGER.info("Start server success. cost time : {} ms", System.currentTimeMillis() - beginTime);
    }

    /**
     * 打印 logo
     */
    private static void printLogo() {
        String logo = "\n" +
                "       _                      __  __                      \n" +
                "      | |                    |  \\/  |                     \n" +
                "      | | ___ _ __ _ __ _   _| \\  / | ___  _   _ ___  ___ \n" +
                "  _   | |/ _ \\ '__| '__| | | | |\\/| |/ _ \\| | | / __|/ _ \\\n" +
                " | |__| |  __/ |  | |  | |_| | |  | | (_) | |_| \\__ \\  __/\n" +
                "  \\____/ \\___|_|  |_|   \\__, |_|  |_|\\___/ \\__,_|___/\\___|\n" +
                "                         __/ |                            \n" +
                "                        |___/                             ";
        LOGGER.info(logo);
    }

    /**
     * 初始化spring
     */
    private static void initSpring() {
        SpringBeanUtils.doLoad();

        LOGGER.info("Init spring context success.");
    }

    /**
     * 初始化服务器
     *
     * @param args
     * @throws Exception
     */
    private static void initServer(String args[]) throws Exception {
        Server server = SpringBeanUtils.getBean(Server.class);

        server.beforeStart();

        if (args != null && args.length > 1) {
            server.start(Integer.valueOf(args[0]));
        } else {
            server.start(Server.DEFAULT_PORT);
        }

        server.afterStart();

        LOGGER.info("Init server success.");
    }
}
